//
//  DIYTableViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/23.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "DIYTableViewController.h"
#import "BlurImageView.h"
#import "DetailModel.h"
#import "DetailTableViewCell.h"
#import "DetailPicTableViewCell.h"
@interface DIYTableViewController ()<UIAlertViewDelegate>
//存放数据解析出来的model
@property (nonatomic, strong) NSMutableArray *stepArray;
@property (nonatomic) BOOL isPrefix;
//图片的高度  和  cell的高度
@property (nonatomic) NSInteger height;
//加载动画
@property (nonatomic,strong) YYAnimationIndicator *animationLoad;
@end

@implementation DIYTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建模糊视图
    BlurImageView *blur = [[BlurImageView alloc] initWithFrame:kBounds];
    [blur sd_setImageWithURL:[NSURL URLWithString:self.blurImg]];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundView = blur;
    
    //加载动画
    [self addAniamtion];
    
    [self dataAnalysisWith:self.albumid];
    //注册cell
    [self.tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"MyCell"];
    [self.tableView registerClass:[DetailPicTableViewCell class] forCellReuseIdentifier:@"YouCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"11111"];
    self.tableView.separatorStyle = NO;
}
//数据解析
- (void)dataAnalysisWith:(NSString *)str {
    NSString *string = [kDetailUrl stringByReplacingOccurrencesOfString:@"参数" withString:str];
     
    [LORequestManger GET:string success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        for (NSDictionary *dic in Dic[@"data"]) {
            NSDictionary *dictionary = dic[@"block"];
            DetailModel *model = [DetailModel shareWithDic:dictionary];
            [self.stepArray addObject:model];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (NSMutableArray *)stepArray {
    if (!_stepArray) {
        _stepArray = [[NSMutableArray alloc] init];
    }
    return _stepArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.stepArray.count;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self.navigationController popViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailModel *model = self.stepArray[indexPath.row];
    //结束动画
    [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
    if (self.stepArray.count <= 1 && [model.article isEqualToString:@""]) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该工艺被作者删除了,再看看别的吧!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
    }
    _isPrefix = [model.article hasPrefix:@"http"];
    if ([model.article isEqualToString:@""] || [model.article isEqualToString:@"、"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"11111" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }else {
        if (!_isPrefix) {
            DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = NO;
            cell.backgroundColor = [UIColor clearColor];
            [cell sendModel:model];
            cell.steplabel.text = model.article;
            return cell;
        }else {
            DetailPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YouCell" forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = NO;
            cell.backgroundColor = [UIColor clearColor];
            self.height = [self ReTurnUrl:model.article];
            [cell setImageWith:model AndHeight:self.height];
            return cell;
        }
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailModel *model = self.stepArray[indexPath.row];
    if ([model.article isEqualToString:@""] || [model.article isEqualToString:@"、"]) {
        return 0;
    }
    if (!_isPrefix) {
        CGRect rect = [model.article boundingRectWithSize:CGSizeMake(kWidth - 30 * 2, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName] context:nil];
        return rect.size.height + 20;
    }else {
        return self.height + 10;
    }
}


//----------------------------
- (NSInteger)ReTurnUrl:(NSString *)string {
    NSInteger length = [string length];
    //NSLog(@"%@",string);
    NSRange rang = [string rangeOfString:@"wh="];
    if (rang.length == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该步骤的图片已被作者删除,只有文字叙述咯!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        //NSLog(@"该步骤已被作者删除,看看其他的吧~");
        return 0;
    }else {
        NSInteger count = rang.location + 3;
        NSString *str = [string substringWithRange:NSMakeRange(count, length - count - 1)];
        NSInteger Length = [str length];
        NSRange Rang = [str rangeOfString:@"."];
        NSString *width = [str substringWithRange:NSMakeRange(0, Rang.location)];
        NSString *height = [str substringWithRange:NSMakeRange(Rang.location + 1, Length - Rang.location - 1)];
        //字符串转换为NSInteger
        NSInteger Width = [width integerValue];
        NSInteger Height = [height integerValue];
        NSInteger number = Height * (kWidth - 30 * 2) / Width + 10;
        return number;
    }
}
//添加动画(加载动画)
- (void)addAniamtion {
    self.animationLoad = [[YYAnimationIndicator alloc] initWithFrame:CGRectMake(kWidth / 2 - 40, (kHeight - 64 - 49) / 2 - 40, 80, 80)];
    [self.animationLoad setLoadText:@"努力加载中....."];
    [self.view addSubview:self.animationLoad];
    [self.animationLoad startAnimation];
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
